package com.itheima.service.impl;

import ch.qos.logback.core.model.conditional.ElseModel;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.ClazzMapper;
import com.itheima.pojo.Clazz;
import com.itheima.pojo.Emp;
import com.itheima.pojo.PageResult;
import com.itheima.service.ClazzService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class ClazzServiceImpl extends ServiceImpl<ClazzMapper, Clazz> implements ClazzService {
    @Autowired
    private EmpService empService;

    @Override
    public PageResult<Clazz> getPageResult(String name, LocalDate begin, LocalDate end, int page, int pageSize) {
        Page<Clazz> clazzPage=Page.of(page,pageSize);
//        lambdaQuery 构建查询条件并执行分页查询
        clazzPage = lambdaQuery()
                .like(name != null && !name.isEmpty(), Clazz::getName, name)
                .between(begin != null && end != null, Clazz::getCreateTime, begin, end)
                .page(clazzPage);

//        查询班主任
//        获取班级信息
        List<Clazz> clazzs = clazzPage.getRecords();
//       获取班主任id
        List<Integer> emps = clazzs.stream().map(clazz -> clazz.getMasterId()).collect(Collectors.toList());

//        根据班主任的id获取班主任信息
          List<Emp> empName=empService.listByIds(emps);

//          循环clazzs集合和empName集合
          clazzs.forEach(clazz -> empName.forEach(emp -> {
//              判断id是否相等
              if (clazz.getMasterId()!=null&&clazz.getMasterId().equals(emp.getId())){
//                  设置班主任名称
                  clazz.setMasterName(emp.getName());
              }
          }));

        // 封装并返回分页结果
        return new PageResult<>(clazzPage.getTotal(), clazzPage.getRecords());
    }

    @Override
    public void save1(Clazz clazz) {
        clazz.setCreateTime(LocalDateTime.now());
        clazz.setUpdateTime(LocalDateTime.now());
        save(clazz);
    }

    @Override
    public void updateById1(Clazz clazz) {
        clazz.setUpdateTime(LocalDateTime.now());
        updateById(clazz);
    }
}
